package com.skytech.component.monitor.enterprise_data_monitoring;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class ShanXiService implements CrawlerScript {

    @Autowired
    private ChromeBrowser chromeBrowser;
    private static final Logger log = LoggerFactory.getLogger(ShanXiService.class);
    private static final String province = "陕西";

    @Autowired
    private SaveDataUtil saveDataUtil;

    @Override
    public void start() {
        ChromeDriver driver = chromeBrowser.getChromeDriver();
        try {
            driver.get("http://113.140.66.227:9777/envinfo_ps/publicity/qylist.do?areacode=");
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            //   driver.switchTo().frame("qylblist");
            List<JSONObject> jsonObjectList = new ArrayList<>();
            partClickNext(driver, null, jsonObjectList);
            detailData(driver, jsonObjectList);
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            driver.quit();
        }


    }

    private void detailData(ChromeDriver driver, List<JSONObject> jsonObjectList) {
        for (JSONObject jsonObject : jsonObjectList) {
            driver.get(jsonObject.get("url").toString());
            String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
            Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
            Elements allElements = parse.getAllElements();
            Elements elements = allElements.select("#zxjcpoint > option:nth-child(n+2)");
            //= allElements.select("#zxjczxsjtbl tr");
            for (Element e : elements) {
                String pointId = e.attr("value").split("·")[0];
                String corpcode = e.attr("value").split("·")[1];
                String url = "http://113.140.66.227:9777/envinfo_ps/publicity/zxjcList?corpcode=" + corpcode + "&pointid=" + pointId + "&startdate=" + LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "&enddate=" + LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                driver.get(url);
                String htmlTmp = driver.findElementByTagName("html").getAttribute("outerHTML");
                Document parseTmp = Jsoup.parse(htmlTmp, driver.getCurrentUrl());
                // Elements allElementsTmp = parseTmp.getAllElements();
                JSONArray jsonObjects = JSONArray.parseArray(parseTmp.getAllElements().select("pre").text());
                List<MonitorData> monitorDataList = new ArrayList<>();
                if (!jsonObjects.isEmpty()) {
                    for (Object object : jsonObjects) {
                        JSONObject jsonObjectNew = JSONObject.parseObject(object.toString());
                        MonitorData monitorData = new MonitorData();
                        monitorData.setId(UUID.randomUUID().toString());
                        monitorData.setCompanyName(jsonObject.getString("企业名称"));
                        monitorData.setProvince(province);
                        monitorData.setArea(jsonObject.getString("行政区"));
                        monitorData.setPollutionType(jsonObject.getString("国控类型"));
                        monitorData.setIndustry(jsonObject.getString("所属行业"));
                        monitorData.setAddress(jsonObject.getString("详细地址"));
                        monitorData.setMonitorPoint(jsonObjectNew.getString("POINTNAME"));
                        monitorData.setMonitorTime(jsonObjectNew.getString("CURDATETIME"));
                        monitorData.setMonitorInfo(jsonObjectNew.getString("ITEMNAME"));
                        monitorData.setMonitorValue(jsonObjectNew.getString("ACCAVGVALUE"));
                        monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        monitorDataList.add(monitorData);
                    }

                    saveDataUtil.saveTag(monitorDataList, province);
                }


            }

        }
    }


    private void partClickNext(ChromeDriver driver, String html, List<JSONObject> jsonObjectList) {

        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        Elements allElements = parse.getAllElements();
        Elements elements = allElements.select("#Form > table > tbody > tr:nth-child(2) > td > div > table.ccefw > tbody > tr:nth-child(n+2)");
        if (!elements.isEmpty()) {
            for (Element e : elements) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("企业名称", e.getElementsByTag("td").get(0).text());
                jsonObject.put("行政区", e.getElementsByTag("td").get(1).text());
                jsonObject.put("国控类型", e.getElementsByTag("td").get(2).text());
                jsonObject.put("所属行业", e.getElementsByTag("td").get(3).text());
                jsonObject.put("详细地址", e.getElementsByTag("td").get(4).text());
                if (!e.getElementsByTag("a").get(0).attr("onclick").contains("该企业为涉密企业，无法查看")) {
                    String corpid = e.getElementsByTag("a").get(0).attr("onclick").split("'")[1];
                    String wrtype = e.getElementsByTag("a").get(0).attr("onclick").split("'")[3];
                    String devid = e.getElementsByTag("a").get(0).attr("onclick").split("'")[5];
                    String corpname = e.getElementsByTag("a").get(0).attr("onclick").split("'")[7];
                    String url = tocorp1(corpid, wrtype, devid, corpname);
                    jsonObject.put("url", url);
                    jsonObjectList.add(jsonObject);
                }
            }
        }
        try {
            driver.findElementByXPath("//*[@id='Form']/table/tbody/tr[2]/td/div/table[2]/tbody/tr/td/div/ul/li/a[text()='下页']").click();
            partClickNext(driver, html, jsonObjectList);
        } catch (Exception e) {
            log.error("点击下页出错！--{}", e.getMessage());
            return;
        }


    }


    private String tocorp1(String corpid, String wrtype, String devid, String corpname) {
        String type = null;
        if (wrtype.equals("废气")) {
            type = "FQ";
        } else if (wrtype.equals("废水")) {
            type = "FS";
        } else if (wrtype.equals("污水处理厂")) {
            type = "WS";
        } else if (wrtype.equals("重金属")) {
            type = "JS";
        } else if (wrtype.equals("危险废物")) {
            type = "WF";
        }
        return "http://113.140.66.227:9777/envinfo_ps/publicity/tocorp?corpid=" + corpid + "&wrtype=" + type + "&devid=" + devid + "&corpname=" + corpname;
    }

}
